<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单 - 校园二手书交易平台</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        .stats-card {
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
        }
        .stats-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            font-size: 24px;
            color: white;
        }
        .stats-info h5 {
            font-size: 1.1rem;
            margin-bottom: 5px;
            color: #666;
        }
        .stats-info h3 {
            font-size: 1.8rem;
            margin: 0;
        }
        .buying-orders {
            background-color: #f8f9fa;
            border-left: 4px solid #007bff;
        }
        .buying-orders .stats-icon {
            background-color: #007bff;
        }
        .selling-orders {
            background-color: #f8f9fa;
            border-left: 4px solid #28a745;
        }
        .selling-orders .stats-icon {
            background-color: #28a745;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-paid {
            background-color: #d4edda;
            color: #155724;
        }
        .status-shipped {
            background-color: #cce5ff;
            color: #004085;
        }
        .status-completed {
            background-color: #d1e7dd;
            color: #0f5132;
        }
        .status-cancelled {
            background-color: #f8d7da;
            color: #721c24;
        }
        .tab-pane {
            padding-top: 20px;
        }
        .navbar-nav .nav-item {
            margin-right: 15px;
        }
        .footer {
            background-color: #343a40;
            color: white;
            padding: 30px 0;
            margin-top: 50px;
        }
        .order-item {
            border: 1px solid #eee;
            border-radius: 5px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        .order-header {
            padding: 10px 15px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #eee;
        }
        .order-body {
            padding: 15px;
        }
        .order-footer {
            padding: 10px 15px;
            background-color: #f8f9fa;
            border-top: 1px solid #eee;
            text-align: right;
        }
        .book-img {
            width: 60px;
            height: 80px;
            object-fit: cover;
            border-radius: 3px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .book-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .book-price {
            font-weight: bold;
            color: #e74c3c;
        }
        .modal-lg {
            max-width: 800px;
        }
        .action-btn {
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" th:href="@{/}">校园二手书交易平台</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/}"><i class="fas fa-home"></i> 首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/book/list}"><i class="fas fa-book"></i> 书籍列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/book/publish}"><i class="fas fa-plus"></i> 发布书籍</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" th:href="@{/book/my-books}">我的书籍</a>
                    </li>
                    <li class="nav-item active">
                        <a class="nav-link" th:href="@{/order/my-orders}">我的订单</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown" sec:authorize="isAuthenticated()">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown">
                            <span sec:authentication="name"></span>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right">
                            <a class="dropdown-item" th:href="@{/user/profile}">个人信息</a>
                            <div class="dropdown-divider"></div>
                            <a class="dropdown-item" th:href="@{/logout}">退出登录</a>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 页面内容 -->
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-shopping-cart"></i> 我的订单</h2>
        </div>
        
        <!-- 统计卡片 -->
        <div class="row">
            <div class="col-md-6">
                <div class="stats-card buying-orders">
                    <div class="stats-icon">
                        <i class="fas fa-shopping-cart"></i>
                    </div>
                    <div class="stats-info">
                        <h5>我购买的</h5>
                        <h3 th:text="${totalBuyingOrders}">0</h3>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="stats-card selling-orders">
                    <div class="stats-icon">
                        <i class="fas fa-store"></i>
                    </div>
                    <div class="stats-info">
                        <h5>我卖出的</h5>
                        <h3 th:text="${totalSellingOrders}">0</h3>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 订单列表标签页 -->
        <ul class="nav nav-tabs" id="ordersTabs" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" id="buying-tab" data-toggle="tab" href="#buying" role="tab" aria-selected="true">
                    我购买的 <span class="badge badge-primary" th:text="${totalBuyingOrders}">0</span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="selling-tab" data-toggle="tab" href="#selling" role="tab" aria-selected="false">
                    我卖出的 <span class="badge badge-success" th:text="${totalSellingOrders}">0</span>
                </a>
            </li>
        </ul>
        
        <div class="tab-content" id="ordersTabContent">
            <!-- 我购买的订单 -->
            <div class="tab-pane fade show active" id="buying" role="tabpanel">
                <div class="order-list mt-3">
                    <!-- 无订单提示 -->
                    <div class="alert alert-info" th:if="${buyingOrders.isEmpty()}">
                        <i class="fas fa-info-circle"></i> 您暂时没有购买的订单记录，赶快去购买吧！
                    </div>
                    
                    <!-- 订单列表 -->
                    <div class="order-item" th:each="order : ${buyingOrders}">
                        <div class="order-header d-flex justify-content-between align-items-center">
                            <div>
                                <span class="mr-3">订单号：<strong th:text="${order.id}"></strong></span>
                                <span class="mr-3">下单时间：<span th:text="${#dates.format(order.createTime, 'yyyy-MM-dd HH:mm')}"></span></span>
                                <span>卖家：<span th:text="${order.sellerName}"></span></span>
                            </div>
                            <div>
                                <span class="status-badge" 
                                      th:classappend="${order.status == 1 ? 'status-pending' : 
                                                       order.status == 2 ? 'status-paid' : 
                                                       order.status == 3 ? 'status-shipped' : 
                                                       order.status == 4 ? 'status-completed' : 'status-cancelled'}"
                                      th:text="${order.status == 1 ? '待付款' : 
                                                order.status == 2 ? '待发货' : 
                                                order.status == 3 ? '待收货' : 
                                                order.status == 4 ? '已完成' : '已支付'}">
                                </span>
                            </div>
                        </div>
                        <div class="order-body">
                            <div class="d-flex">
                                <div class="mr-3">
                                    <img th:src="${order.book != null && order.book.imageUrl != null ? order.book.imageUrl : '/img/default-book.jpg'}" class="book-img" alt="Book Cover">
                                </div>
                                <div class="flex-grow-1">
                                    <div class="book-title" th:text="${order.book != null ? order.book.title : '未知书籍'}"></div>
                                    <div class="text-muted small">
                                        <span class="mr-3" th:text="${order.book != null && order.book.author != null ? '作者：' + order.book.author : ''}"></span>
                                        <span th:text="${order.book != null && order.book.category != null ? '分类：' + order.book.category : ''}"></span>
                                    </div>
                                    <div class="mt-2">
                                        <span class="book-price" th:text="'¥' + ${order.bookPrice}"></span>
                                        <span class="text-muted ml-2">数量：1</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="order-footer">
                            <a th:href="@{'/order/detail/' + ${order.id}}" class="btn btn-sm btn-outline-primary">查看详情</a>
                            
                            <!-- 待付款 -->
                            <button th:if="${order.status == 1}" class="btn btn-sm btn-success action-btn"
                                    th:onclick="'payOrder(' + ${order.id} + ')'">
                                <i class="fas fa-credit-card"></i> 支付
                            </button>
                            
                            <!-- 待付款/已取消 -->
                            <button th:if="${order.status == 1}" class="btn btn-sm btn-danger action-btn" 
                                    th:onclick="'cancelOrder(' + ${order.id} + ')'">
                                <i class="fas fa-ban"></i> 取消订单
                            </button>
                            
                            <!-- 待收货 -->
                            <button th:if="${order.status == 3}" class="btn btn-sm btn-primary action-btn" 
                                    th:onclick="'confirmOrder(' + ${order.id} + ')'">
                                <i class="fas fa-check"></i> 确认收货
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 我卖出的订单 -->
            <div class="tab-pane fade" id="selling" role="tabpanel">
                <div class="order-list mt-3">
                    <!-- 无订单提示 -->
                    <div class="alert alert-info" th:if="${sellingOrders.isEmpty()}">
                        <i class="fas fa-info-circle"></i> 您暂时没有卖出的订单记录，发布更多优质书籍来吸引买家吧！
                    </div>
                    
                    <!-- 订单列表 -->
                    <div class="order-item" th:each="order : ${sellingOrders}">
                        <div class="order-header d-flex justify-content-between align-items-center">
                            <div>
                                <span class="mr-3">订单号：<strong th:text="${order.id}"></strong></span>
                                <span class="mr-3">下单时间：<span th:text="${#dates.format(order.createTime, 'yyyy-MM-dd HH:mm')}"></span></span>
                                <span>买家：<span th:text="${order.buyerName}"></span></span>
                            </div>
                            <div>
                                <span class="status-badge" 
                                      th:classappend="${order.status == 1 ? 'status-pending' : 
                                                       order.status == 2 ? 'status-paid' : 
                                                       order.status == 3 ? 'status-shipped' : 
                                                       order.status == 4 ? 'status-completed' : 'status-cancelled'}"
                                      th:text="${order.status == 1 ? '待付款' : 
                                                order.status == 2 ? '待发货' : 
                                                order.status == 3 ? '待收货' : 
                                                order.status == 4 ? '已完成' : '已支付'}">
                                </span>
                            </div>
                        </div>
                        <div class="order-body">
                            <div class="d-flex">
                                <div class="mr-3">
                                    <img th:src="${order.book != null && order.book.imageUrl != null ? order.book.imageUrl : '/img/default-book.jpg'}" class="book-img" alt="Book Cover">
                                </div>
                                <div class="flex-grow-1">
                                    <div class="book-title" th:text="${order.book != null ? order.book.title : '未知书籍'}"></div>
                                    <div class="text-muted small">
                                        <span class="mr-3" th:text="${order.book != null && order.book.author != null ? '作者：' + order.book.author : ''}"></span>
                                        <span th:text="${order.book != null && order.book.category != null ? '分类：' + order.book.category : ''}"></span>
                                    </div>
                                    <div class="mt-2">
                                        <span class="book-price" th:text="'¥' + ${order.bookPrice}"></span>
                                        <span class="text-muted ml-2">数量：1</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="order-footer">
                            <a th:href="@{'/order/detail/' + ${order.id}}" class="btn btn-sm btn-outline-primary">查看详情</a>
                            
                            <!-- 待发货 -->
                            <button th:if="${order.status == 2}" class="btn btn-sm btn-primary action-btn" 
                                    onclick="openShippingModal(this)" th:attr="data-order-id=${order.id}">
                                <i class="fas fa-shipping-fast"></i> 发货
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 发货信息模态框 -->
    <div class="modal fade" id="shippingModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">填写发货信息</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="shippingForm">
                        <input type="hidden" id="orderIdForShipping" name="orderId">
                        <div class="form-group">
                            <label for="trackingNumber">物流单号</label>
                            <input type="text" class="form-control" id="trackingNumber" name="trackingNumber" required>
                            <small class="form-text text-muted">请输入快递单号，确保买家可以查询物流信息</small>
                        </div>
                        <div class="form-group">
                            <label for="courierCompany">快递公司</label>
                            <select class="form-control" id="courierCompany" name="courierCompany">
                                <option value="顺丰速运">顺丰速运</option>
                                <option value="中通快递">中通快递</option>
                                <option value="圆通速递">圆通速递</option>
                                <option value="申通快递">申通快递</option>
                                <option value="韵达快递">韵达快递</option>
                                <option value="EMS">EMS</option>
                                <option value="京东物流">京东物流</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmShippingBtn">确认发货</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 微信支付二维码弹窗 -->
    <div class="modal fade" id="wechatPayModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content text-center">
                <div class="modal-header">
                    <h5 class="modal-title">微信扫码支付</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="wechat-qrcode"></div>
                    <p class="mt-3">请使用微信扫一扫完成支付</p>
                    <div id="wechat-pay-status" class="text-danger"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer th:replace="fragments/footer :: footer"></footer>

    <!-- JavaScript引用 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.2/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    
    <script th:inline="javascript">
        /*<![CDATA[*/
        // 支付订单
        function payOrder(orderId) {
            $.ajax({
                type: 'POST',
                url: '/booktrading/order/pay/' + orderId,
                success: function(res) {
                    if (res.code_url) {
                        $('#wechat-qrcode').empty();
                        new QRCode(document.getElementById("wechat-qrcode"), {
                            text: res.code_url,
                            width: 200,
                            height: 200
                        });
                        $('#wechat-pay-status').text('');
                        $('#wechatPayModal').modal('show');
                        pollPayStatus(orderId);
                    } else {
                        alert(res.message || '获取支付二维码失败');
                    }
                },
                error: function() {
                    alert('请求失败，请稍后再试！');
                }
            });
        }
        
        // 取消订单
        function cancelOrder(orderId) {
            if (confirm('确定要取消此订单吗？此操作不可恢复！')) {
                $.ajax({
                    type: 'POST',
                    url: /*[[@{/order/cancel/}]]*/ '' + orderId,
                    success: function(response) {
                        if (response.success) {
                            alert('订单已取消！');
                            location.reload();
                        } else {
                            alert('取消失败：' + response.message);
                        }
                    },
                    error: function() {
                        alert('请求失败，请稍后再试！');
                    }
                });
            }
        }
        
        // 确认收货
        function confirmOrder(orderId) {
            if (confirm('确认已收到商品吗？确认后订单将完成！')) {
                $.ajax({
                    type: 'POST',
                    url: /*[[@{/order/confirm/}]]*/ '' + orderId,
                    success: function(response) {
                        if (response.success) {
                            alert('确认收货成功！');
                            location.reload();
                        } else {
                            alert('确认收货失败：' + response.message);
                        }
                    },
                    error: function() {
                        alert('请求失败，请稍后再试！');
                    }
                });
            }
        }
        
        // 打开发货模态框
        function openShippingModal(button) {
            var orderId = $(button).data('order-id');
            $('#orderIdForShipping').val(orderId);
            $('#shippingModal').modal('show');
        }
        
        // 确认发货
        $(document).ready(function() {
            $('#confirmShippingBtn').click(function() {
                var orderId = $('#orderIdForShipping').val();
                var trackingNumber = $('#trackingNumber').val();
                
                if (!trackingNumber) {
                    alert('请输入快递单号！');
                    return;
                }
                
                $.ajax({
                    type: 'POST',
                    url: /*[[@{/order/ship/}]]*/ '' + orderId,
                    data: {
                        trackingNumber: trackingNumber
                    },
                    success: function(response) {
                        $('#shippingModal').modal('hide');
                        if (response.success) {
                            alert('发货成功！');
                            location.reload();
                        } else {
                            alert('发货失败：' + response.message);
                        }
                    },
                    error: function() {
                        $('#shippingModal').modal('hide');
                        alert('请求失败，请稍后再试！');
                    }
                });
            });
        });

        var payStatusTimer = null;
        function pollPayStatus(orderId) {
            if (payStatusTimer) clearInterval(payStatusTimer);
            payStatusTimer = setInterval(function() {
                $.get('/booktrading/order/pay-status/' + orderId, function(res) {
                    if (res.paid) {
                        clearInterval(payStatusTimer);
                        $('#wechatPayModal').modal('hide');
                        alert('支付成功！');
                        location.reload();
                    }
                });
            }, 2000);
        }
        $('#wechatPayModal').on('hidden.bs.modal', function () {
            if (payStatusTimer) clearInterval(payStatusTimer);
        });
        /*]]>*/
    </script>
</body>
</html> 